package org.ytor.core.sysapi.codegen.api;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.ytor.common.enums.MimeType;
import org.ytor.core.DownloadMapper;
import org.ytor.core.sysapi.codegen.logic.CodeGenLogic;
import org.ytor.core.sysapi.codegen.model.TableMeta;
import org.ytor.core.sysapi.codegen.service.IMetaService;
import org.ytor.core.util.RespUtil;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

/**
 * created by yangtong on 2025/4/6 下午5:31
 * <p>
 * 代码生成器接口
 */
@RestController
@RequestMapping("/sys/codegen")
@AllArgsConstructor
@Tag(name = "代码生成器")
public class CodeGenController {

    private final CodeGenLogic codeGenService;
    private final IMetaService metaService;

    @Operation(summary = "获取数据源的所有数据库", description = "获取数据源的所有数据库")
    @GetMapping(value = "/queryCatalogs")
    public List<String> queryCatalogs() throws SQLException {
        return metaService.listCatalogs();
    }

    @Operation(summary = "获取指定数据库的所有schema", description = "获取指定数据库的所有schema")
    @GetMapping(value = "/querySchemas")
    public List<String> querySchemas(@RequestParam String catalog) throws SQLException {
        return metaService.listSchemas(catalog);
    }

    @Operation(summary = "查询数据库表", description = "查询数据库表")
    @GetMapping(value = "/queryTables")
    public List<TableMeta> queryTables(@RequestParam String catalog, String schema, String table) throws SQLException {
        return metaService.listTables(catalog, schema, table);
    }

    @Operation(summary = "根据表名称生成代码", description = "根据表名称生成代码")
    @DownloadMapper(value = "/genCodeByTable", mime = MimeType.APPLICATION_ZIP)
    public void genCodeByTable(@RequestParam String basePath, @RequestParam String module, @RequestParam String tableName, HttpServletResponse response) throws IOException {
        byte[] data = codeGenService.gen(basePath, module, null, tableName);
        RespUtil.downloadResponse(tableName + ".zip", MimeType.APPLICATION_ZIP);
        response.getOutputStream().write(data);
        response.flushBuffer();
    }
}
